<template>
  <div class="students-management">
    <!-- 搜索区域 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="学号">
            <el-input v-model="filterForm.studentId" placeholder="请输入学号" @keyup.enter="queryStudentDetail" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" @click="queryStudentDetail">查询</el-button>
            <el-button type="default" @click="resetFilter">重置</el-button>
            <el-button type="success" @click="addDialogVisible=true">添加学生</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog v-model="queryDialogVisible" title="学生信息查询结果" width="50%" @close="handleQueryDialogClose">
      <el-form :model="queryStudentInfo" label-width="120px">
        <el-form-item label="学号">
          <el-input v-model="queryStudentInfo.studentId" disabled></el-input>
        </el-form-item>
        <el-form-item label="学生姓名">
          <el-input v-model="queryStudentInfo.studentName" disabled></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-input v-model="queryStudentInfo.gender" disabled></el-input>
        </el-form-item>
        <el-form-item label="班级ID">
          <el-input v-model="queryStudentInfo.classId" disabled></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="queryStudentInfo.age" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="queryStudentInfo.phone" disabled></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱">
          <el-input v-model="queryStudentInfo.email" disabled></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 学生列表 -->
    <el-card class="student-list-card">
      <div class="table-container">
        <el-table :data="studentList" stripe border @row-dblclick="handleRowClick" style="width: 100%;" max-height="500px">
          <el-table-column prop="studentId" label="学号"></el-table-column>
          <el-table-column prop="studentName" label="学生姓名"></el-table-column>
          <el-table-column prop="gender" label="性别" width="80"></el-table-column>
          <el-table-column prop="classId" label="班级ID" width="120"></el-table-column>
          <el-table-column prop="age" label="年龄" width="80"></el-table-column>
          <el-table-column prop="phone" label="联系电话"></el-table-column>
          <el-table-column prop="email" label="电子邮箱" min-width="100"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <el-pagination
          class="pagination"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加学生对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加学生" width="50%" @close="handleAddDialogClose">
      <el-form :model="addForm" label-width="120px" :rules="addFormRules">
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="addForm.studentId"></el-input>
        </el-form-item>
        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="addForm.studentName"></el-input>
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="addForm.password" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="addForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="班级ID" prop="classId">
          <el-input v-model="addForm.classId"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="addForm.age" :min="10" :max="100"></el-input-number>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑学生对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑学生" width="50%" @close="handleEditDialogClose">
      <el-form :model="editForm" ref="editFormRef" label-width="120px" :rules="editFormRules">
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="editForm.studentId" disabled></el-input>
        </el-form-item>
        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="editForm.studentName"></el-input>
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="editForm.password" type="password" show-password :disabled="!changePassword"></el-input>
          <el-checkbox v-model="changePassword">修改密码</el-checkbox>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="班级ID" prop="classId">
          <el-input v-model="editForm.classId"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="editForm.age" :min="10" :max="100"></el-input-number>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, computed, onMounted } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";

// 筛选条件
const filterForm = reactive({
  studentId: "",
  classId: "",
});

// 表格数据和分页
const studentList = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// 查询对话框相关
const queryDialogVisible = ref(false);
const queryStudentInfo = ref({
  studentId: "",
  studentName: "",
  gender: "",
  classId: "",
  age: "",
  phone: "",
  email: "",
});

// 添加学生相关
const addDialogVisible = ref(false);
const addForm = ref({
  studentId: "",
  studentName: "",
  password: "",
  phone: "",
  email: "",
  gender: "",
  classId: "",
  age: 0
});

// 编辑学生相关
const editDialogVisible = ref(false);
const editForm = ref({
  studentId: "",
  studentName: "",
  password: "",
  phone: "",
  email: "",
  gender: "",
  classId: "",
  age: 0
});
const changePassword = ref(false);
const editFormRef = ref(null);

const queryStudentDetail = async () => {
  const studentId = filterForm.studentId;
  if (!studentId) {
    ElMessage.warning("请输入学号");
    return;
  }
  try {
    const response = await axios.get(`/students/getStudentDetail?studentId=${studentId}`);
    if (response.data.flag) {
      queryStudentInfo.value = response.data.result;
      queryDialogVisible.value = true;
    } else {
      ElMessage.error(response.data.reason || "查询失败");
    }
  } catch (error) {
    console.error("查询出错:", error);
    ElMessage.error("查询时发生错误，请稍后重试");
  }
};

// 确认添加
const submitAddForm = async () => {
  const formData = new FormData();
  formData.append("studentId", addForm.value.studentId);
  formData.append("classId", addForm.value.classId);
  formData.append("password", addForm.value.password);
  formData.append("studentName", addForm.value.studentName);
  if (addForm.value.phone) {
    formData.append("phone", addForm.value.phone);
  }
  if (addForm.value.email) {
    formData.append("email", addForm.value.email);
  }
  if (addForm.value.gender) {
    formData.append("gender", addForm.value.gender);
  }
  if (addForm.value.age) {
    formData.append("age", addForm.value.age);
  }

  try {
    const response = await axios.post('/students/addStudent', formData);
    if (response.data.flag) {
      ElMessage.success("添加成功");
      addDialogVisible.value = false;

      addForm.value = {
        studentId: "",
        studentName: "",
        password: "",
        phone: "",
        email: "",
        gender: "",
        classId: "",
        age: 0,
      };

      fetchStudentList();
    } else {
      ElMessage.error("添加失败：" + response.data.message || "未知错误");
    }
  } catch (error) {
    console.log(error);
    ElMessage.error("添加失败，请稍后重试");
  }
};

// 编辑
const handleEdit = (row) => {
  editDialogVisible.value = true;
  editForm.value = { ...row };
};

// 提交编辑
const submitEditForm = async () => {
  await editFormRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    const formData = new FormData();
    formData.append("studentId", editForm.value.studentId);
    formData.append("phone", editForm.value.phone);
    formData.append("email", editForm.value.email);
    if (editForm.value.studentName) {
      formData.append("studentName", editForm.value.studentName);
    }
    if (editForm.value.gender) {
      formData.append("gender", editForm.value.gender);
    }
    if (editForm.value.classId) {
      formData.append("classId", editForm.value.classId);
    }
    if (editForm.value.age) {
      formData.append("age", editForm.value.age);
    }
    if (changePassword.value) {
      formData.append("password", editForm.value.password);
    }

    try {
      const response = await axios.post(`/students/updateStudent`, formData);
      if (response.data.flag) {
        ElMessage.success("学生信息更新成功！");
        editDialogVisible.value = false;
        editFormRef.value.resetFields();
        fetchStudentList();

      } else {
        ElMessage.error("更新失败！");
      }
    } catch (error) {
      console.log(error);
    }
  })
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.studentId = "";
  filterForm.classId = "";
  fetchStudentList();
};

// 添加表单验证规则
const addFormRules = computed(() => ({
  studentId: [
    { required: true, message: "请输入学号", trigger: "blur" },
    { len: 12, message: "学号长度必须为12位", trigger: "blur" },
  ],
  studentName: [
    { required: true, message: "请输入学生姓名", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入登录密码", trigger: "blur" },
    { min: 6, message: "密码长度至少为6位", trigger: "blur" }
  ],
  classId: [
    { required: true, message: "请输入班级ID", trigger: "blur" },
    { len: 10, message: "班级ID长度必须为10位", trigger: "blur" }
  ],
  email: [
    { type: "email", message: "请输入正确的邮箱格式", trigger: ["blur", "change"] }
  ],
}));

// 编辑表单验证规则
const editFormRules = computed(() => ({
  studentName: [
    { required: true, message: "请输入学生姓名", trigger: "blur" }
  ],
  password: [
    { required: changePassword.value, message: "请输入登录密码", trigger: "blur" },
    { min: 6, message: "密码长度至少为6位", trigger: "blur" }
  ],
  classId: [
    { required: true, message: "请输入班级ID", trigger: "blur" },
    { len: 10, message: "班级ID长度必须为10位", trigger: "blur" }
  ],
  email: [
    { type: "email", message: "请输入正确的邮箱格式", trigger: ["blur", "change"] }
  ],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" }
  ]
}));

// 生命周期钩子
onMounted(async () => {
  await fetchStudentList();
});

// 获取学生列表
const fetchStudentList = async () => {
  try {
    // const params = {
    //   ...filterForm,
    //   page: currentPage.value,
    //   size: pageSize.value,
    // };
    const formData = new FormData();
    formData.append("classId",filterForm.classId);
    formData.append("studentId",filterForm.studentId);
    formData.append("page",currentPage.value);
    formData.append("size",pageSize.value);
    // console.log("当前页码：", currentPage.value);
    // console.log("每页大小：", pageSize.value);
    // console.log(params);
    const response = await axios.post("/students/getStudentList", formData);
    console.log(response.data.result);
    studentList.value = response.data.result || [];
    total.value = response.data.total || 0;
  } catch (error) {
    console.error("获取学生列表失败", error);
    ElMessage.error("获取学生列表失败，请稍后重试");
  }
};

const handleQueryDialogClose = () => {
  queryDialogVisible.value = false;
  queryStudentInfo.value = {
    studentId: "",
    studentName: "",
    gender: "",
    classId: "",
    age: "",
    phone: "",
    email: "",
  };
};

// 添加对话框关闭时处理
const handleAddDialogClose = () => {
  addDialogVisible.value = false;
};

// 编辑对话框关闭时处理
const handleEditDialogClose = () => {
  editDialogVisible.value = false;
  editForm.value = {}; // 重置表单对象
  changePassword.value = false; // 重置密码修改标记
};

// 删除学生
const handleDelete = (student) => {
  ElMessageBox.confirm(
      `确定要删除学生 "${student.studentName}" (${student.studentId}) 吗？删除后将无法恢复。`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "danger",
      }
  ).then(async () => {
    try {
      const response = await axios.delete(`/students/deleteStudent?studentId=${student.studentId}`);
      if (response.data.flag) {
        ElMessage.success("学生删除成功");
        fetchStudentList();
      } else {
        ElMessage.error(response.data.message || "学生删除失败");
      }
    } catch (error) {
      console.error("删除学生失败", error);
      ElMessage.error("删除学生失败，请稍后重试");
    }
  }).catch(() => {
    // 取消操作
  });
};

// 双击行编辑
const handleRowClick = (row) => {
  handleEdit(row);
};

// 分页控制
const handleSizeChange = (newSize) => {
  currentPage.value = 1; //重置页大小时返回第一页
  pageSize.value = newSize;
  fetchStudentList();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchStudentList();
};
</script>

<style scoped>
.students-management {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.student-list-card {
  height: auto;
  margin-bottom: 20px;
}

.table-container {
  height: 500px;
  overflow-y: auto;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>